package com.education.ai.controller;

import com.education.ai.entity.Teacher;
import com.education.ai.model.dto.PasswordUpdateRequest;
import com.education.ai.model.dto.ProfileUpdateRequest;
import com.education.ai.service.TeacherService;
import com.education.ai.util.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Optional;

/**
 * 教师控制器
 */
@RestController
@RequestMapping("/api/teachers")
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:8080", "http://localhost:8081"}, allowCredentials = "true")
public class TeacherController {
    
    private static final Logger logger = LoggerFactory.getLogger(TeacherController.class);
    
    @Autowired
    private TeacherService teacherService;
    
    /**
     * 获取所有教师
     */
    @GetMapping
    public ResponseEntity<List<Teacher>> getAllTeachers() {
        return ResponseEntity.ok(teacherService.getAllTeachers());
    }
    
    /**
     * 获取当前登录教师的个人信息
     */
    @GetMapping("/profile")
    public ResponseEntity<?> getCurrentTeacherProfile(HttpServletRequest request) {
        // 从请求属性中获取教师ID
        String teacherId = (String) request.getAttribute("teacherId");
        if (teacherId == null) {
            logger.error("获取教师个人信息失败：未找到教师ID");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ResponseResult.error("未找到教师ID，请重新登录"));
        }
        
        // 根据教师ID查询教师信息
        Optional<Teacher> teacher = teacherService.getTeacherByTeacherId(teacherId);
        if (!teacher.isPresent()) {
            logger.error("获取教师个人信息失败：教师ID {} 不存在", teacherId);
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ResponseResult.error("教师不存在"));
        }
        
        // 返回教师信息
        logger.info("成功获取教师 {} 的个人信息", teacherId);
        return ResponseEntity.ok(ResponseResult.success(teacher.get()));
    }
    
    /**
     * 更新当前登录教师的个人信息
     */
    @PutMapping("/profile")
    public ResponseEntity<?> updateCurrentTeacherProfile(
            @RequestBody ProfileUpdateRequest profileRequest,
            HttpServletRequest request) {
        
        // 从请求属性中获取教师ID
        Integer teacherId = (Integer) request.getAttribute("teacherId");
        if (teacherId == null) {
            logger.error("更新教师个人信息失败：未找到教师ID");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ResponseResult.error("未找到教师ID，请重新登录"));
        }
        
        // 根据教师ID查询教师信息
        Optional<Teacher> optionalTeacher = teacherService.getTeacherByTeacherId(teacherId.toString());
        if (!optionalTeacher.isPresent()) {
            logger.error("更新教师个人信息失败：教师ID {} 不存在", teacherId);
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ResponseResult.error("教师不存在"));
        }
        
        // 更新教师信息
        Teacher teacher = optionalTeacher.get();
        teacher.setName(profileRequest.getName());
        teacher.setPhone(profileRequest.getPhoneNumber());
        teacher.setEmail(profileRequest.getEmail());
        teacher.setSubject(profileRequest.getSubject());
        
        // 保存更新后的教师信息
        Teacher updatedTeacher = teacherService.saveTeacher(teacher);
        logger.info("成功更新教师 {} 的个人信息", teacherId);
        
        return ResponseEntity.ok(ResponseResult.success(updatedTeacher));
    }
    
    /**
     * 更新当前登录教师的密码
     */
    @PutMapping("/password")
    public ResponseEntity<?> updatePassword(
            @RequestBody PasswordUpdateRequest passwordRequest,
            HttpServletRequest request) {
        
        // 从请求属性中获取教师ID
        Integer teacherId = (Integer) request.getAttribute("teacherId");
        if (teacherId == null) {
            logger.error("更新密码失败：未找到教师ID");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ResponseResult.error("未找到教师ID，请重新登录"));
        }
        
        try {
            // 更新密码
            boolean updated = teacherService.updatePassword(
                    teacherId.toString(),
                    passwordRequest.getCurrentPassword(),
                    passwordRequest.getNewPassword()
            );
            
            if (updated) {
                logger.info("成功更新教师 {} 的密码", teacherId);
                return ResponseEntity.ok(ResponseResult.success("密码更新成功"));
            } else {
                logger.warn("更新密码失败：当前密码不正确，教师ID: {}", teacherId);
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(ResponseResult.error("当前密码不正确"));
            }
        } catch (Exception e) {
            logger.error("更新密码时发生错误，教师ID: " + teacherId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("密码更新失败: " + e.getMessage()));
        }
    }
    
    /**
     * 根据ID获取教师
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getTeacherById(@PathVariable Long id) {
        return teacherService.getTeacherById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 根据教师工号获取教师
     */
    @GetMapping("/teacher-id/{teacherId}")
    public ResponseEntity<?> getTeacherByTeacherId(@PathVariable String teacherId) {
        return teacherService.getTeacherByTeacherId(teacherId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 根据学科获取教师
     */
    @GetMapping("/subject/{subject}")
    public ResponseEntity<List<Teacher>> getTeachersBySubject(@PathVariable String subject) {
        return ResponseEntity.ok(teacherService.getTeachersBySubject(subject));
    }
    
    /**
     * 根据姓名搜索教师
     */
    @GetMapping("/search")
    public ResponseEntity<List<Teacher>> searchTeachers(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String subject) {
        
        if (name != null && subject != null) {
            return ResponseEntity.ok(teacherService.searchTeachersBySubjectAndName(subject, name));
        } else if (name != null) {
            return ResponseEntity.ok(teacherService.searchTeachersByName(name));
        } else if (subject != null) {
            return ResponseEntity.ok(teacherService.getTeachersBySubject(subject));
        } else {
            return ResponseEntity.ok(teacherService.getAllTeachers());
        }
    }
    
    /**
     * 创建教师
     */
    @PostMapping
    public ResponseEntity<?> createTeacher(@RequestBody Teacher teacher) {
        // 检查教师工号是否已存在
        if (teacherService.isTeacherIdExists(teacher.getTeacherId())) {
            Map<String, Object> response = new HashMap<>();
            response.put("error", "教师工号已存在");
            response.put("teacherId", teacher.getTeacherId());
            return ResponseEntity.status(HttpStatus.CONFLICT).body(response);
        }
        
        Teacher createdTeacher = teacherService.saveTeacher(teacher);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdTeacher);
    }
    
    /**
     * 更新教师
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateTeacher(@PathVariable Long id, @RequestBody Teacher teacher) {
        return teacherService.getTeacherById(id)
                .map(existingTeacher -> {
                    // 检查如果工号变更，确认新工号不存在
                    if (!existingTeacher.getTeacherId().equals(teacher.getTeacherId()) && 
                            teacherService.isTeacherIdExists(teacher.getTeacherId())) {
                        Map<String, Object> response = new HashMap<>();
                        response.put("error", "教师工号已存在");
                        response.put("teacherId", teacher.getTeacherId());
                        return ResponseEntity.status(HttpStatus.CONFLICT).body(response);
                    }
                    
                    teacher.setId(id);
                    return ResponseEntity.ok(teacherService.saveTeacher(teacher));
                })
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 删除教师
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteTeacher(@PathVariable Long id) {
        return teacherService.getTeacherById(id)
                .map(teacher -> {
                    teacherService.deleteTeacher(id);
                    return ResponseEntity.ok().build();
                })
                .orElse(ResponseEntity.notFound().build());
    }
} 